/**
 *  两种调用方式
	var template1="我是{0}，今年{1}了";
	var template2="我是{name}，今年{age}了";
	var result1=template1.format("loogn",22);
	var result2=template2.format({name:"loogn",age:22});
	两个结果都是"我是loogn，今年22了
 */
var _ = require('lodash')
String.prototype.format = function(args) {
	var result = this;
	if (arguments.length > 0) {
		if (arguments.length == 1 && args instanceof Object) {
			result = this.replace(/\{([\w.]+)\}/g, function(substring, str) {
				let val = _.get(args, str, '');
				if (val instanceof Object) {
					val = JSON.stringify(val);
				}
				return val;
			});
		} else {
			for (var i = 0; i < arguments.length; i++) {
				if (arguments[i] != undefined) {
					var reg = new RegExp("({[" + i + "]})", "g");
					result = result.replace(reg, arguments[i]);
				}
			}
		}
	}
	return result;
}



/**
 * 判断字符串是否为空
 * @obj 
 */
export function isNotBlank(obj) {
	return obj != undefined && obj != null && obj.toString().length > 0
}

let moment = require('moment');
moment.locale('zh-cn');
var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	formatL: function(milliseconds) {
		milliseconds = parseInt(milliseconds);
		var diff = Date.now() - milliseconds;
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		return moment(milliseconds).format('YYYY-MM-DD');
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};
import store from '@/store'
/**
 * 生成图片路径
 */
export function getImgUrl(type, id,imgType) {
	return store.state.imgUrl + type + "/" + id + "."+(imgType==undefined?'png':imgType);
}
export default {
	// Vue.js的插件应当有一个公开方法 install。这个方法的第一个参数是 Vue 构造器，第二个参数是一个可选的选项对象。
	install: function(Vue) {
		Vue.prototype.isNotBlank = (param) => isNotBlank(param)
		Vue.prototype.getImgUrl = (type, id,imgType) => getImgUrl(type, id,imgType)
		Vue.prototype.dateUtils = dateUtils
		Vue.prototype.moment = moment
	}
}
